package com.qwc.blog.security.controller;

import com.alibaba.fastjson.JSON;
import com.qwc.blog.security.entity.LoginUserDto;
import com.qwc.blog.security.entity.LoginUserVo;
import com.qwc.blog.security.service.LoginService;
import com.qwc.blog.security.service.VerificationService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qwc
 * @Date 2021/10/15 12:39
 */
@Slf4j
@RestController
@RequestMapping
public class LoginController {

    @Autowired
    private VerificationService verificationService;

    @Autowired
    private LoginService loginService;

    @GetMapping("code")
    public ResponseEntity<Object> getCode() {
        return ResponseEntity.ok(verificationService.getCode());
    }

    @PostMapping("/login")
    public ResponseEntity<Object> login(@Validated @RequestBody LoginUserDto userDto, HttpServletRequest request) {
        verificationService.checkCode(userDto.getUuid(), userDto.getCode());
        return ResponseEntity.ok(loginService.login(userDto.getUsername(), userDto.getPassword()));
    }

    @GetMapping("/getProfile")
    public ResponseEntity<Object> getProfile(HttpServletRequest request) {
        Claims claims = loginService.getProfile(request);
        Map<Object, Object> map = new HashMap<>(16);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("Expiration", dateFormat.format(claims.getExpiration()));
        map.put("Audience", claims.getAudience());
        map.put("id", claims.getId());
        map.put("IssuedAt", claims.getIssuedAt());
        map.put("Issuer", claims.getIssuer());
        map.put("NotBefore", claims.getNotBefore());
        map.put("Subject", JSON.parseObject(claims.getSubject(), LoginUserVo.class));
        return ResponseEntity.ok(map);
    }
}
